<script>
  import FieldLabel from "./FieldLabel.svelte";
  import { createEventDispatcher } from "svelte";

  const dispatch = createEventDispatcher();

  export let label = "";
  export let required = false;
  export let value = "";
  export let placeholder = "请选择";
  export let options = [];
  export let labelKey = "label";
  export let valueKey = "value";
  export let disabled = false;
  export let error = "";
  export let readonly = false;
  export let clearable = false;
  export let searchable = false;

  let showDropdown = false;
  let searchText = "";
  let dropdownContainer;

  // 验证函数
  export function validate() {
    if (required && (value === "" || value === null || value === undefined)) {
      error = `请选择${label}`;
      return false;
    }
    error = "";
    return true;
  }

  export function clearError() {
    error = "";
  }

  export function setError(msg) {
    error = msg;
  }

  // 获取选项的标签
  function getOptionLabel(option) {
    if (typeof option === "string" || typeof option === "number") {
      return option.toString();
    }
    return (
      option[labelKey] ||
      option.label ||
      option.name ||
      option
    ).toString();
  }

  // 获取选项的值
  function getOptionValue(option) {
    if (typeof option === "string" || typeof option === "number") {
      return option;
    }
    return option[valueKey] || option.value || option.id || option;
  }

  // 获取当前选中项的显示文本
  $: selectedLabel = (() => {
    if (value === "" || value === null || value === undefined) {
      return "";
    }

    const selectedOption = options.find((option) => {
      const optionValue = getOptionValue(option);
      return optionValue == value; // 使用宽松比较
    });

    return selectedOption ? getOptionLabel(selectedOption) : String(value);
  })();

  // 过滤选项
  $: filteredOptions = (() => {
    if (!searchable || !searchText.trim()) {
      return options;
    }

    return options.filter((option) => {
      const label = getOptionLabel(option).toLowerCase();
      return label.includes(searchText.toLowerCase());
    });
  })();

  // 打开下拉菜单
  function openDropdown() {
    if (disabled) return;
    showDropdown = true;
    searchText = "";

    // 聚焦到搜索框
    if (searchable) {
      setTimeout(() => {
        const searchInput = dropdownContainer?.querySelector(".search-input");
        if (searchInput) {
          searchInput.focus();
        }
      }, 100);
    }
  }

  // 关闭下拉菜单
  function closeDropdown() {
    showDropdown = false;
    searchText = "";
  }

  // 选择选项
  function selectOption(option) {
    const newValue = getOptionValue(option);
    value = newValue;
    closeDropdown();

    // 清除错误
    if (error) {
      error = "";
    }

    // 派发change事件
    dispatch("change", { value: newValue });
  }

  // 清除选择
  function clearSelection(event) {
    event.stopPropagation();
    value = "";
    closeDropdown();

    dispatch("change", { value: "" });
  }

  // 点击外部关闭
  function handleClickOutside(event) {
    if (dropdownContainer && !dropdownContainer.contains(event.target)) {
      closeDropdown();
    }
  }

  // 键盘事件处理
  function handleKeydown(event) {
    if (event.key === "Escape") {
      closeDropdown();
    }
  }
</script>

<svelte:window on:click={handleClickOutside} on:keydown={handleKeydown} />

<div class="form-field">
  <FieldLabel {label} {required} />

  <div class="select-field-container" bind:this={dropdownContainer}>
    {#if readonly}
      <div class="readonly-value">{selectedLabel || "-"}</div>
    {:else}
      <div
        class="select-trigger"
        class:disabled
        class:error={!!error}
        class:open={showDropdown}
        on:click={openDropdown}
        tabindex={disabled ? -1 : 0}
      >
        <div class="select-content">
          {#if selectedLabel}
            <span class="selected-text">{selectedLabel}</span>
          {:else}
            <span class="placeholder-text">{placeholder}</span>
          {/if}
        </div>

        <div class="select-actions">
          {#if clearable && selectedLabel && !disabled}
            <button
              class="clear-btn"
              on:click={clearSelection}
              tabindex="-1"
              type="button"
            >
              ×
            </button>
          {/if}

          <svg
            class="arrow-icon"
            class:rotated={showDropdown}
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="none"
          >
            <path
              d="M8.00042 8.78028L11.3003 5.48047L12.2431 6.42328L8.00042 10.6659L3.75781 6.42328L4.70062 5.48047L8.00042 8.78028Z"
              fill="#474747"
            />
          </svg>
        </div>
      </div>

      {#if showDropdown && !disabled}
        <div class="dropdown-panel">
          {#if searchable}
            <div class="search-box">
              <input
                type="text"
                bind:value={searchText}
                placeholder="搜索选项..."
                class="search-input"
              />
            </div>
          {/if}

          <div class="options-list">
            {#if filteredOptions.length === 0}
              <div class="no-options">
                {searchText ? "未找到匹配项" : "暂无选项"}
              </div>
            {:else}
              {#each filteredOptions as option}
                {@const optionValue = getOptionValue(option)}
                {@const optionLabel = getOptionLabel(option)}
                <div
                  class="option-item"
                  class:selected={optionValue == value}
                  on:click={() => selectOption(option)}
                  on:keydown={(e) => e.key === "Enter" && selectOption(option)}
                  tabindex="0"
                >
                  <span class="option-label">{optionLabel}</span>
                  {#if option.description}
                    <span class="option-description">{option.description}</span>
                  {/if}
                </div>
              {/each}
            {/if}
          </div>
        </div>
      {/if}
    {/if}
  </div>

  {#if error}
    <div class="field-error">{error}</div>
  {/if}
</div>

<style>
  .form-field {
    margin-bottom: 24px;
  }

  .select-field-container {
    position: relative;
    width: 100%;
  }

  .select-trigger {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    background: #fff;
    cursor: pointer;
    font-size: 14px;
    color: #121212;
    transition:
      border-color 0.2s,
      box-shadow 0.2s;
    box-sizing: border-box;
    min-height: 36px;
  }

  .select-trigger:hover:not(.disabled) {
    border-color: rgba(69, 81, 229, 0.5);
  }

  .select-trigger:focus {
    outline: none;
    border-color: rgba(69, 81, 229, 1);
    box-shadow: 0px 0px 2px 0px rgba(69, 81, 229, 0.6);
  }

  .select-trigger.disabled {
    background: #f5f5f5;
    color: #ccc;
    cursor: not-allowed;
  }

  .select-trigger.error {
    border-color: #ee4646;
    background: rgba(238, 70, 70, 0.05);
  }

  .select-content {
    flex: 1;
    min-width: 0;
  }

  .selected-text {
    color: #121212;
  }

  .placeholder-text {
    color: #ccc;
  }

  .select-actions {
    display: flex;
    align-items: center;
    gap: 4px;
    flex-shrink: 0;
  }

  .clear-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
    border-radius: 2px;
    font-size: 15px;
    line-height: 1;
  }

  .clear-btn:hover {
    color: #da3633;
    background: rgba(238, 70, 70, 0.1);
  }

  .arrow-icon {
    color: #666;
    transition: transform 0.2s;
  }

  .arrow-icon.rotated {
    transform: rotate(180deg);
  }

  .dropdown-panel {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    margin-top: 2px;
    overflow: hidden;
    max-height: 240px;
  }

  .search-box {
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;
  }

  .search-input {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #e0e0e0;
    border-radius: 3px;
    font-size: 13px;
    box-sizing: border-box;
  }

  .search-input:focus {
    outline: none;
    border-color: rgba(69, 81, 229, 1);
  }

  .options-list {
    max-height: 200px;
    overflow-y: auto;
  }

  .option-item {
    padding: 8px 12px;
    cursor: pointer;
    transition: background-color 0.2s;
    border-left: 2px solid transparent;
  }

  .option-item:hover {
    background: #f6f8fa;
  }

  .option-item.selected {
    background: rgba(69, 81, 229, 0.1);
  }

  .option-item:focus {
    outline: none;
    background: #f6f8fa;
  }

  .option-label {
    display: block;
    font-size: 14px;
    color: #121212;
  }

  .option-description {
    display: block;
    font-size: 12px;
    color: #666;
    margin-top: 2px;
    line-height: 1.3;
  }

  .no-options {
    padding: 12px;
    text-align: center;
    color: #999;
    font-size: 13px;
  }

  .readonly-value {
    padding: 8px 0;
    font-size: 14px;
    color: #333;
    line-height: 1.5;
    min-height: 20px;
  }

  .field-error {
    margin-top: 4px;
    font-size: 12px;
    color: rgba(238, 70, 70, 1);
  }
</style>
